package com.freesky.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.freesky.common.config.ProjectConfig;
import com.freesky.common.core.domain.AjaxResult;
import com.freesky.common.enums.ExportStatusEnum;
import com.freesky.common.utils.SecurityUtils;
import com.freesky.common.utils.StringUtils;
import com.freesky.common.utils.file.FileUtils;
import com.freesky.common.utils.uuid.UUID;
import com.freesky.system.domain.TExportRecord;
import com.freesky.system.domain.TImportRecord;
import com.freesky.system.mapper.TExportRecordMapper;
import com.freesky.system.mapper.TImportRecordMapper;
import com.freesky.system.service.ITExportRecordService;
import com.freesky.system.service.ITImportRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

/**
 * 导入文件记录Service业务层处理
 *
 * @author lwl
 * @date 2022-06-02
 */
@Service
public class TImportRecordServiceImpl implements ITImportRecordService {

    @Autowired
    private TImportRecordMapper importRecordMapper;

    @Override
    public TImportRecord selectTImportRecordById(Long id) {
        return importRecordMapper.selectTImportRecordById(id);
    }

    @Override
    public List<TImportRecord> selectTImportRecordList(TImportRecord tImportRecord) {
        return importRecordMapper.selectTImportRecordList(tImportRecord);
    }

    @Override
    public AjaxResult insertTImportRecord(TImportRecord tImportRecord) {
        return AjaxResult.success(importRecordMapper.insert(tImportRecord));
    }

    @Override
    public AjaxResult insertTImportRecord(MultipartFile file, TImportRecord tImportRecord) {
        try {
            //带路径的文件名
            String fileName = UUID.randomUUID() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            File dest = new File(ProjectConfig.getUploadPath());
            file.transferTo(new File(ProjectConfig.getDownloadPath() + fileName));

            //获取文件的路径
            tImportRecord.setFileUrl(dest.getAbsolutePath());
            tImportRecord.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
            tImportRecord.setFileName(fileName);
            tImportRecord.setFileOriName(file.getOriginalFilename());

            return AjaxResult.success(importRecordMapper.insert(tImportRecord));
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return AjaxResult.error("导入文件记录发生错误", e);
        }
    }

    @Override
    public int updateTImportRecord(TImportRecord tImportRecord) {
        return importRecordMapper.update(tImportRecord);
    }

    @Override
    public int deleteTImportRecordByIds(Long[] ids) {
        return importRecordMapper.deleteTImportRecordByIds(ids);
    }

    @Override
    public int deleteTImportRecordById(Long id) {
        return importRecordMapper.deleteTImportRecordById(id);
    }

    @Override
    public AjaxResult fileExcel(Long id, Long fileType, HttpServletResponse response, HttpServletRequest request) {
        try {
            //根据id获得当前记录信息
            TImportRecord tImportRecord = importRecordMapper.selectTImportRecordById(id);

            //System.out.println(JSON.toJSONString(tImportRecord));
            //判断文件名是否合法
            if (!FileUtils.checkAllowDownload(tImportRecord.getFileName())) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", tImportRecord.getFileName()));
            }

            String realFileName = null;
            String filePath = null;
            if (fileType==1) {
                realFileName = tImportRecord.getFileName();
                filePath = ProjectConfig.getDownloadPath() + tImportRecord.getFileName();
            } else if (fileType==2) {
                realFileName = tImportRecord.getExFileName();
                filePath = ProjectConfig.getDownloadPath() + tImportRecord.getExFileName();
            }

            //System.out.println(filePath);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            return AjaxResult.success("导入成功!");
        } catch (Exception e) {
            return AjaxResult.error("导入失败!");
        }
    }

    @Override
    public List<TImportRecord> selectImportBizType(String importBizType) {
        String userId = String.valueOf(SecurityUtils.getUserId());
        return importRecordMapper.selectTImportRecordBizType(importBizType,userId);
    }

}
